package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.app.func.MyAllWindowFunction;
import com.atguigu.bean.UserActiveBack;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.MyClickHouseUtil;
import com.atguigu.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws0201UserChangeWindow {
    public static void main(String[] args) throws Exception {
        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
//        tableEnv.getConfig().setIdleStateRetention(Duration.ofSeconds(18*60+5));
        //  状态后端设置
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");
        //2.从kafka DWD层读取dwd_traffic_page_view的数据
        DataStreamSource<String> kafkaDS = env.fromSource(MyKafkaUtil.getKafkaSource("dwd_traffic_page_view", "user_change_window"), WatermarkStrategy.<String>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<String>() {
            @Override
            public long extractTimestamp(String s, long l) {
                JSONObject jsonObject = JSON.parseObject(s);
                return jsonObject.getLong("ts");
            }
        }), "kafka-source");
        kafkaDS.print("kafkaDS>>>>>");
        //3.过滤，将数据转换为JSONOBJECT,并keyby
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                JSONObject jsonObject = JSON.parseObject(s);
                String userId = jsonObject.getJSONObject("common").getString("uid");
                JSONObject page = jsonObject.getJSONObject("page");
                String lastPageId = page.getString("last_page_id");
                //if (userId != null && (lastPageId == null || lastPageId.equals("login"))) {
                    collector.collect(jsonObject);
                //}
            }
        });

        jsonObjDS.print("jsonObjDS--》");
        KeyedStream<JSONObject, String> keyedUidDS = jsonObjDS.keyBy(r -> r.getJSONObject("common").getString("uid"));
        //4.将数据转换为JavaBean,并补充字段
        SingleOutputStreamOperator<UserActiveBack> userChangeDS = keyedUidDS.flatMap(new RichFlatMapFunction<JSONObject, UserActiveBack>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("uid-state", String.class);
                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public void flatMap(JSONObject jsonObject, Collector<UserActiveBack> collector) throws Exception {
                //获取状态
                String lastDt = valueState.value();
                Long ts = jsonObject.getLong("ts");
                String curDt = DateFormatUtil.toYmdHms(ts);
                Long curCount = 0L;
                Long backCount = 0L;
                if (lastDt == null) {
                    curCount = 1L;
                } else {
                    if (!lastDt.equals(curDt)) {
                        curCount = 1L;
                        if (DateFormatUtil.toTs(curDt) - DateFormatUtil.toTs(lastDt) >= 8 * 24 * 3600 * 1000L) {
                            backCount = 1L;
                        }
                    }

                }
                if (curCount == 1L){
                    collector.collect(new UserActiveBack("","",curCount,backCount,0L));
                }
            }
        });
        userChangeDS.print("userChangeDS==>");

        //5.开窗 聚合
        SingleOutputStreamOperator<UserActiveBack> reduceDS = userChangeDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10))).reduce(new ReduceFunction<UserActiveBack>() {
            @Override
            public UserActiveBack reduce(UserActiveBack userChange, UserActiveBack t1) throws Exception {
                userChange.setCurCount(userChange.getCurCount() + t1.getCurCount());
                userChange.setBackCount(userChange.getBackCount() + t1.getBackCount());
                return userChange;
            }
        }, new MyAllWindowFunction<UserActiveBack, TimeWindow>());


        //6.写出
        reduceDS.print("reduceDS>>>>>>");
        reduceDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_user_change_window values (?,?,?,?,?)"));


        env.execute();
    }

}
